package org.mspring.mlog.web.admin;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.web.BaseAdminController;
import org.mspring.mlog.entity.ConfigEntity;
import org.mspring.mlog.common.constants.ConfigGroup;
import org.mspring.mlog.service.ConfigEntityService;
import org.mspring.mlog.support.TabItem;
import org.mspring.nbee.common.utils.CollectionUtils;
import org.mspring.nbee.common.utils.RequestUtils;
import org.mspring.nbee.web.support.WebContext;
import org.mspring.nbee.web.view.json.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Gao Youbo
 * @since 2015-01-03 18:13
 */
@Controller
@RequestMapping("/admin/config")
@TabItem(item = "200110")
public class ConfigController extends BaseAdminController {
    private ConfigEntityService configEntityService;

    @RequestMapping("/base")
    @TabItem(item = "200110005")
    public String base(WebContext context, Model model) {
        return "/admin/config/base";
    }

    @RequestMapping("/base/do")
    @ResponseBody
    public JsonResult doBase(WebContext context, Model model) {
        List<ConfigEntity> configs = new ArrayList<>();
        Map<String, Object> map = RequestUtils.getRequestParams(context.getRequest());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (StringUtils.startsWith(entry.getKey(), "config.")) {
                String name = StringUtils.substringAfter(entry.getKey(), "config.");
                String value = null;
                if (entry.getValue() != null) {
                    if (entry.getValue() instanceof List) {
                        List<String> list = (List<String>) entry.getValue();
                        String[] array = CollectionUtils.asArray(list);
                        value = StringUtils.join(array, ",");
                    } else {
                        value = entry.getValue().toString();
                    }
                }
                ConfigEntity config = new ConfigEntity();
                config.setGroupName(ConfigGroup.BASE);
                config.setName(name);
                config.setValue(value);
                configs.add(config);
            }
        }
        configEntityService.insertOrUpdateConfigs(configs);
        return JsonResult.getJsonResult(map);
    }

    @Autowired
    public void setConfigEntityService(ConfigEntityService configEntityService) {
        this.configEntityService = configEntityService;
    }
}
